<template>
  <a-modal width="600px" v-model:visible="visible" :title="title" @before-ok="onOk">
    <a-form ref="formRef" :model="form" size="medium" auto-label-width>
      <a-form-item label="账号名称" field="remark">
        <a-input placeholder="请输入账号名称" v-model="form.remark" allow-clear></a-input>
      </a-form-item>
      <a-form-item label="域名" field="domain">
        <a-input placeholder="请输入域名" v-model="form.domain" allow-clear></a-input>
      </a-form-item>
      <a-form-item label="appKey" field="appKey">
        <a-input placeholder="请输入appKey" v-model="form.appKey" allow-clear></a-input>
      </a-form-item>
      <a-form-item label="状态" field="status">
        <a-switch v-model="form.status" :unchecked-value="0" :checked-value="1"></a-switch>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { accountAppend } from '@/apis'
import { Message } from '@arco-design/web-vue'
import { reAssign } from '@/utils/common'

const emit = defineEmits(['getTableData'])

const title = computed(() => (form.id ? '平台账户编辑' : '平台账户新增'))
const visible = ref(false)
const formRef = ref()

const form = reactive({
  id: undefined,
  domain: undefined,
  appKey: undefined,
  remark: undefined,
  status: undefined
})

// 打开编辑框并回显表单值
const addOrEdit = (item) => {
  reAssign(form, item)
  item && formRef.value?.validate()
  visible.value = true
}

// 点击确认添加/编辑
const onOk = async () => {
  const validateResult = await formRef.value?.validate()
  if (validateResult) return false
  await accountAppend(form)
  Message.success('操作成功')
  emit('getTableData')
  return true
}

provide('formRef', formRef)
defineExpose({ addOrEdit })
</script>
